package com.chiry.enjoyandroid;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.chiry.enjoyandroid.retrofit.HttpbinService;

import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

public class MainActivity extends AppCompatActivity {

    private Retrofit retrofit;
    private HttpbinService httpbinService;

    private static String TAG = "MainActivity";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        retrofit = new Retrofit.Builder().baseUrl("http://www.httpbin.org/").build();
        httpbinService = retrofit.create(HttpbinService.class);
        View viewById = findViewById(R.id.btn_retrofit_post);
        viewById.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
            synTaskHttp();
            }
        });

    }


    public void synTaskHttp(){
        Call<ResponseBody> call = httpbinService.postRequest("chiry", "123");
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                try {
                    Toast.makeText(MainActivity.this,response.body().string(),Toast.LENGTH_SHORT).show();
                    Log.i(TAG, "onResponse: "+response.body().string());// response.body().string()只能被那一次
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
               // Toast.makeText(MainActivity.this, "error", Toast.LENGTH_SHORT).show();
            }
        });
    }

}
